import React, { Component } from 'react';
import {
  Table,
  Row,
  Col,
  Input,
  Icon,
  Button,
  Modal,
  Form,
  Radio,
  Tooltip,
  Popconfirm,
  message,
  Spin,
} from 'antd';
import { UserList, createUser, updateUser, deleteUser } from '@/api/user/index';
import styles from './index.less';
import moment from 'moment';

const CollectionCreateForm = Form.create({
  name: 'form_in_modal',
  mapPropsToFields(props) {
    return {
      title: Form.createFormField({
        ...props.title,
        value: props.title.value,
      }),
      phone: Form.createFormField({
        ...props.phone,
        value: props.phone.value,
      }),
    };
  },
})(
  // eslint-disable-next-line
  class extends React.Component {
    render() {
      const {
        visible,
        onCancel,
        onCreate,
        form,
        Title,
        OnText,
        PasswordStatus,
        ongetList,
      } = this.props;
      const { getFieldDecorator } = form;
      return (
        <Modal visible={visible} title={Title} okText={OnText} onCancel={onCancel} onOk={onCreate}>
          <Form layout="vertical">
            <Form.Item label="姓名" hasFeedback={true}>
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入姓名' }],
              })(<Input />)}
            </Form.Item>
            <Form.Item label="手机号码" hasFeedback={true}>
              {getFieldDecorator('phone', {
                rules: [{ required: true, message: '请输入手机号码' }],
              })(<Input />)}
            </Form.Item>
            {PasswordStatus ? (
              <Form.Item label="密码">
                {getFieldDecorator('passWord', {
                  rules: [{ required: true, message: '请输入密码' }],
                })(<Input.Password />)}
              </Form.Item>
            ) : (
              <div />
            )}
          </Form>
        </Modal>
      );
    }
  }
);
function _onCancel() {
  message.info('取消');
}
export default class User extends Component {
  state = {
    dataSource: [],
    RowData: '', //点击表格行的数据
    OnText: '创建',
    columns: [
      {
        title: '用户名称',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        render: create_time => `${moment(create_time).format('YYYY-MM-DD hh:mm:ss')}`,
      },
      {
        title: '操作',
        dataIndex: '',
        key: 'k',
        render: text => {
          return (
            <div>
              <Tooltip placement="top" title="查看">
                <Button
                  size="small"
                  icon="check"
                  onClick={() => {
                    this.ShowList(text);
                  }}
                  className={styles.ButtonStyle}
                />
              </Tooltip>
              <Tooltip placement="top" title="修改">
                <Button
                  size="small"
                  type="primary"
                  icon="edit"
                  onClick={() => {
                    this.ShowEdit(text);
                  }}
                  className={styles.ButtonStyle}
                />
              </Tooltip>
              <Popconfirm
                title="确定删除吗"
                onConfirm={() => {
                  this._onConfirm(text);
                }}
                onCancel={_onCancel}
                icon={<Icon type="delete" style={{ color: 'red' }} />}
              >
                <Button size="small" type="danger" icon="delete" />
              </Popconfirm>
            </div>
          );
        },
      },
    ],
    loading: false,
    visible: false,
    Modal: {
      title: '添加',
      OnText: '添加',
    },
    ModalForm: {
      title: {
        value: '',
      },
      phone: {
        value: '',
      },
    },
    PasswordStatus: true, //查看密码显示状态
    EditStatus: false, //修改状态
    current: 1, //第几页
    total: 0, //总数
    spinning: true, //加载指示器的状态
  };
  _onConfirm = e => {
    //修改
    deleteUser(e.id).then(res => {
      let data = JSON.parse(res);
      if (data.code === 0) {
        message.success('删除成功');
        this._getList();
      } else {
        message.error('删除失败');
      }
    });
  };
  ShowList = val => {
    //查看
    this.setState({
      visible: true,
      Modal: {
        title: '查看',
        OnText: '确定',
      },
      PasswordStatus: false,
      //设置点击弹出模态框值
      ModalForm: {
        title: {
          value: val.userName,
        },
        phone: {
          value: val.phone,
        },
      },
    });
  };
  componentWillMount() {
    this._getList();
  }
  _getList = (page = 1, limit = 10) => {
    let data = {
      page,
      limit,
    };
    UserList(data).then(res => {
      console.log(res);
      if (res && res.code === 0) {
        this.setState({
          dataSource: res.data,
          total: res.total,
          spinning: false,
        });
      }
    });
  };
  //设置输入框得值为空
  emitEmpty = () => {
    this.userNameInput.focus();
    this.setState({ userName: '' });
  };
  //获取输入框的值
  onChangeUserName = e => {
    this.setState({ userName: e.target.value });
  };
  showModal = () => {
    this.setState({
      visible: true,
      Modal: {
        title: '添加',
        OnText: '添加',
      },
      PasswordStatus: true,
      EditStatus: false,
      ModalForm: {
        title: {
          value: '',
        },
        phone: {
          value: '',
        },
      },
    });
  };
  ShowEdit = text => {
    this.setState({
      visible: true,
      Modal: {
        title: '修改',
        OnText: '修改',
      },
      PasswordStatus: true,
      ModalForm: {
        title: {
          value: text.userName,
        },
        phone: {
          value: text.phone,
        },
        id: text.id,
      },
      EditStatus: true,
    });
  };
  handleCancel = () => {
    this.setState({ visible: false });
  };

  handleCreate = () => {
    if (this.state.PasswordStatus) {
      const form = this.formRef.props.form;
      form.validateFields((err, values) => {
        if (err) {
          return;
        }
        console.log('Received values of form: ', values);
        form.resetFields();
        const data = {
          phone: Number(values.phone),
          userName: values.title,
          passWord: values.passWord,
        };
        if (this.state.EditStatus) {
          //修改
          updateUser(this.state.ModalForm.id, data).then(res => {
            if (res.code === 0) {
              message.success(res.msg);
              this.setState({
                visible: false,
              });
              this._getList();
            } else {
              message.error(res.msg);
            }
          });
        } else {
          //添加
          createUser(data).then(res => {
            if (res.code === 0) {
              message.success(res.msg);
              this.setState({
                visible: false,
              });
              this._getList();
            } else {
              message.error(res.msg);
            }
          });
        }
      });
    }
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };
  changePage = (page, pageSize) => {
    this.setState({
      spinning: true,
    });
    this._getList(page, 10);
    this.setState({
      current: page,
    });
    console.log(`page=${page}`, `pageSize=${pageSize}`);
  };
  onShowSizeChange = (current, pageSize) => {
    this.setState({
      spinning: true,
    });
    this._getList(current, pageSize);
    this.setState({
      current: current,
    });
    console.log(`current=${current}`, `pageSize=${pageSize}`);
  };
  render() {
    const { userName } = this.state;
    const ModalForm = this.state.ModalForm;
    const { visible, loading } = this.state;
    const suffix = userName ? <Icon type="close-circle" onClick={this.emitEmpty} /> : null;
    return (
      <Row className={styles.container}>
        <Col span={24}>
          <div style={{ margin: 20 }}>
            <Input
              style={{ width: 200 }}
              placeholder="请输入搜索的账号"
              prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />}
              suffix={suffix}
              value={userName}
              onChange={this.onChangeUserName}
              ref={node => (this.userNameInput = node)}
            />
            <Button
              type="primary"
              icon="plus"
              shape="circle"
              size="small"
              onClick={this.showModal}
              style={{ marginLeft: 20 }}
            />
            <CollectionCreateForm
              wrappedComponentRef={this.saveFormRef}
              visible={this.state.visible}
              onCancel={this.handleCancel}
              {...ModalForm}
              PasswordStatus={this.state.PasswordStatus}
              onCreate={this.handleCreate}
              ongetList={() => {
                this._getList();
              }}
              Title={this.state.Modal.title}
              OnText={this.state.Modal.OnText}
            />
          </div>
          <Spin tip="加载中..." spinning={this.state.spinning}>
            <Table
              style={{ padding: 20 }}
              pagination={{
                showSizeChanger: true,
                current: this.state.current,
                total: this.state.total,
                onChange: this.changePage,
                onShowSizeChange: this.onShowSizeChange,
              }}
              dataSource={this.state.dataSource}
              columns={this.state.columns}
              onRow={(record, index) => {
                return {
                  onClick: event => {
                    this.setState({
                      RowData: record,
                    });
                  }, // 点击行
                  onDoubleClick: event => {},
                  onContextMenu: event => {},
                  onMouseEnter: event => {}, // 鼠标移入行
                  onMouseLeave: event => {},
                };
              }}
            />
          </Spin>
        </Col>
      </Row>
    );
  }
}
